package com.test3;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.MessageDigest;

import org.apache.commons.lang3.StringUtils;

import sun.misc.BASE64Encoder;

@SuppressWarnings("restriction")
public class Test7 {

	public static void main(String[] args) {
		
		String path = "C:/Users/domains90/Desktop/999.png";
			
		String base = Base64Utils.convertFileToBase64ByFile(path);
		System.err.println("IMAGE BASE64:"+base);
			
//		System.err.println("MD5 byUrl:"+getMD5ByUrl("https://tmp.s.weshaketv.com/1234567/lizhao/999.png"));
//		
//		System.err.println("MD5 byFile:"+getMD5ByFile(path));

	}
	
	/**
	 * 获取本地图片md5
	 * @param path 本地路劲
	 * */
	public static String getMD5ByFile(String path) {
		File file = new File("C:/Users/domains90/Desktop/999.png");
		
		try {
			InputStream inputStream = new FileInputStream(file);

			return md5(inputStream);
			
		} catch (Exception e) {
			throw new RuntimeException(e.getLocalizedMessage());
		}
	}

	/**
	 * 获取网络图片 md5
	 * @param URLName 网络图片地址
	 * */
	public static String getMD5ByUrl(String URLName) {

		try {

			URL url = new URL(URLName);
			
			InputStream inputStream = new BufferedInputStream(url.openStream());
			
			return md5(inputStream);
			
		} catch (Exception e) {
			
			throw new RuntimeException(e.getLocalizedMessage());
			
		}
		
	}
	

	private static String md5(InputStream inputStream) {		
		String name = StringUtils.EMPTY;
		try(InputStream stream = inputStream;) {
			byte[] bytes = new byte[1024];

			int len = 0;

			MessageDigest messagedigest = MessageDigest.getInstance("MD5");

			while ((len = inputStream.read(bytes)) > 0) {

				messagedigest.update(bytes, 0, len);

			}
			name = MD5Util.bufferToHex(messagedigest.digest());
		} catch (Exception e) {
			throw new RuntimeException(e.getLocalizedMessage());

		}
		return name;
	}
	

}
